#include "imapstudialog.h"
#include "02-socket/01-imap/ui_imapstudialog.h"
#include "../../11-util/02-log_manager/logmanager.h"
#include "../../b-model/04-task/01-imap_task/imaptask.h"
#include "../../b-model/01-mail_model/folder_model/foldermodel.h"
#include "../../11-util/01-md5_manager/md5manager.h"
#include "../../11-util/01-string_codec_manager/stringcodecmanager.h"
static const QString TAG = "ImapStuDialog";

static Logger * imapLogger = LogManager::getMissionLogger("__imap");


/**
 * 用"作为分隔符,进行处理.
 * @brief getFullNameFromLine_A
 * @param line
 * @return
 */
QString getFullNameFromLine_A(QString line) {
    QStringList components = line.split("\"");
    //移除最后一个元素,在目前样本解析结果来看,必定为一个空字符串.
    components.pop_back();
    QString rawFullName = components.last();
    QString fullName = StringCodecManager::imapUtf7Decode(rawFullName);
    return fullName;
}

ImapStuDialog::ImapStuDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::ImapStuDialog)
{
    ui->setupUi(this);
    folderDatasource = new FolderDatasource();
    LogManager::debug("CreateImapTaskThread","before");
    taskThread = new ImapTaskThread(this);
    taskThread->start();
    LogManager::debug("CreateImapTaskThread","after");
    QStringList list = QStringList();
    list << "收件箱" << "重要邮件" << "已发送" << "草稿箱";
    stringDatasource = new QStringListModel(list);

    ui->tv_folder->setModel(folderDatasource);
     // ui->tv_folder->setModel(stringDatasource);
    ui->tv_folder->show();

    // connect(taskThread->parseThread, &ImapParseThread::connectFinish,[=](QString raw){
    //     QString fmt = "%1 handle in main thread";
    //     LogManager::debug(fmt.arg(QString::number(((long long))QThread::currentThreadId())),"ImapStuDialog");
    //      this->ui->te_server->setText(raw);
    // });

    connect(taskThread->parseThread, &ImapParseThread::connectFinish,this,&ImapStuDialog::onConnectFinish);

    connect(taskThread->parseThread,&ImapParseThread::sendEvent,this,&ImapStuDialog::onEvent);




    QObject::connect(this, &ImapStuDialog::connectFinish2,[=](QString raw){
        QString fmt = "%1 handle in main thread";
        imapLogger->debug(fmt.arg(QString::number((long long)QThread::currentThreadId())),"ImapStuDialog");
        this->ui->te_server->setText(raw);
    });
}

void ImapStuDialog::onEvent(ImapTaskType type,QVariant ret,QVariant raw) {
    QString fmt = "current thread id is %1";
    imapLogger->debug(TAG,"onConnectFinish","after",fmt.arg(QString::number((long long)QThread::currentThreadId())));
    QString rawRes = ret.toString();
    switch(type) {
    case ImapTaskType::FolderList:
    {
        QStringList list = rawRes.split("\r\n");
        //移除最后的一个结束标志\r\n
        list.pop_back();
        //移除倒数第二行的 A01 OK LIST completed
        list.pop_back();
        QVector<FolderModel *>* folders = new QVector<FolderModel *>();
        for (int i = 0 ;i < list.length();i++) {
        // for (int i = 0 ;i < 2; i++) {
            QString folderInfo = list.at(i);
            QString fullName = getFullNameFromLine_A(folderInfo);
            FolderModel * f = new FolderModel(fullName,0,0,FolderType::Inbox);
            folders->append(f);
        }
        this->folderDatasource->appendRows(folders);
        break;
    }
    default :{
        break;
    }
    }

    this->ui->te_server->setText(rawRes);
}


void ImapStuDialog::onConnectFinish(QString ret) {
    QString fmt = "current thread id is %1";
    imapLogger->debug(TAG,"onConnectFinish","after",fmt.arg(QString::number((long long)QThread::currentThreadId())));
    this->ui->te_server->setText(ret);
}

ImapStuDialog::~ImapStuDialog()
{
    delete ui;
}

void ImapStuDialog::on_pushButton_clicked()
{
    // this->mSocket = new QTcpSocket(this);
    // QString serverIp1 = "172.16.10.30";
    // QString serverIp2 = "172.16.10.110";
    // this->mSocket->connectToHost(serverIp2,143);
    // connect(this->mSocket, &QTcpSocket::readyRead, this, &ImapStuDialog::onSocketReceiveData);
    //创建链接任务.
    //f是在parse线程调用的,需要回到主线程中显示.
    ui->te_client->setText("开始连接...");
    QString fmt = "%1 create connect task";
    LogManager::debug(fmt.arg(QString::number((long long)QThread::currentThreadId())),"ImapStuDialog");
    auto f = [this](QVariant ret ,QString raw){
        // auto mainF = [this,raw](QString res) {
        //      this->ui->te_server->setText(raw);
        // };
        // emit connectFinish2(raw);
        qDebug()<<"there is msg from server:" << raw;
    };
    ImapTask * task = new ImapTask("",ImapTaskType::Connect,f);
    taskThread->addTask(task);

}

void ImapStuDialog::onSocketReceiveData() {
    QByteArray buffer;
    //读取缓冲区数据
    buffer = this->mSocket->readAll();
    QString str = "";
    if(!buffer.isEmpty()){
        str+= buffer;
    }
    this->ui->te_server->setText(str);
    qDebug()<<"there is msg from server:" << str;
}

void ImapStuDialog::on_pushButton_2_clicked()
{
    QString cmd = "";
    cmd += "A01 LOGIN " + this->user + " " + this->password + "\r\n";
    // this->sendCmd(cmd);
    ui->te_client->setText("登录中...");
    auto f = [this](QVariant ret,QString raw){
        this->ui->te_server->setText(raw);
    };
    ImapTask * task = new ImapTask(cmd,ImapTaskType::Login,f);
    taskThread->addTask(task);
}


void ImapStuDialog::on_pushButton_3_clicked()
{
    this->mSocket->disconnectFromHost();
    this->mSocket->close();
}


void ImapStuDialog::on_pushButton_4_clicked()
{

}

void ImapStuDialog::sendCmd(QString cmd) {
     this->ui->te_client->setText(cmd);
    this->mSocket->write(cmd.toUtf8().constData());
    this->ui->te_client->setText(cmd);
    //发送.
    this->mSocket->flush();
}


/**
 * 如何将这个发送请求和收到的结果的处理函数,绑定到一起? 请求 和 返回处理 需要一一对应.
 * 思路1:
 * 将请求和返回处理绑定为一个Task? 有返回时
 * @brief ImapStuDialog::on_pushButton_5_clicked
 */
void ImapStuDialog::on_pushButton_5_clicked()
{
    QString cmd = "A01 LIST \"\" \"*\"\r\n";
    ui->te_client->setText("Root文件夹列表:");
    ImapTask * task = new ImapTask(cmd,ImapTaskType::FolderList,nullptr);
    taskThread->addTask(task);
    // this->sendCmd(cmd);
}


/**
 * @brief ImapStuDialog::on_btn_sendCmd_clicked
 * 发送自定义命令
 * 程序帮助用户增加\r\n.
 */
void ImapStuDialog::on_btn_sendCmd_clicked()
{
    QString str = this->ui->te_cmd->toPlainText();
    if(str.length() > 0) {
        str+="\r\n";
        this->sendCmd(str);
    }
}


void ImapStuDialog::on_pushButton_8_clicked()
{
    QString cmd = "A02 SELECT INBOX\r\n";
    this->sendCmd(cmd);
}

/**
 * 查看当前文件夹的所有邮件的index
 * @brief ImapStuDialog::on_pushButton_9_clicked
 */
void ImapStuDialog::on_pushButton_9_clicked()
{
    QString cmd = "A03 SEARCH ALL\r\n";
    this->sendCmd(cmd);
}



/**
 * 查看邮件UID
 * @brief ImapStuDialog::on_pushButton_7_clicked
 */
void ImapStuDialog::on_pushButton_7_clicked()
{
    QString cmd = "A03 FETCH 1 UID\r\n";
    this->sendCmd(cmd);
}

/**
 * 查看邮件subject
 * @brief ImapStuDialog::on_pushButton_10_clicked
 */
void ImapStuDialog::on_pushButton_10_clicked()
{
    QString cmd = "A03 FETCH 1 BODY[HEADER]\r\n";
    this->sendCmd(cmd);
}


/**
 * 注销
 * @brief ImapStuDialog::on_pushButton_11_clicked
 */
void ImapStuDialog::on_pushButton_11_clicked()
{
    QString cmd = "A03 LOGOUT\r\n";
    this->sendCmd(cmd);
}


void ImapStuDialog::on_pushButton_12_clicked()
{
    QString cmd = "A03 FETCH 1 (UID BODY[HEADER])\r\n";
    this->sendCmd(cmd);
}

/**
 * 获取ENVELOPE
 * @brief ImapStuDialog::on_pushButton_13_clicked
 */
void ImapStuDialog::on_pushButton_13_clicked()
{
    QString cmd = "A03 FETCH 1 (ENVELOPE)\r\n";
    this->sendCmd(cmd);
}


void ImapStuDialog::on_btn_addFolder_clicked()
{

    FolderModel * f = new FolderModel();
    f->name = "我的收件箱";
    f->fullName = "xxx";
    QVector<FolderModel *> * v = new QVector<FolderModel *>();
    v->append(f);
    folderDatasource->appendRows(v);
}

